package afcp.alumni.file;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import afcp.alumni.model.db.MemberUtils;

/**
 * 
 * @author aorylamballe
 * @deprecated Le chargement du fichier Excel est fait d'un seul coup. Cause des
 *             problèmes de mémoire quand le fichier est trop gros. Google App
 *             Engine fournit 100 Mo pour la JVM, ce qui est dépassé avec le
 *             chargement d'un fichier Excel de 900 lignes.
 */
@Deprecated
public class ExcelReader implements FileReader {
	
	private InputStream inputStream;
	private Sheet sheet;
	private Iterator<Row> rowIterator;
	
	public ExcelReader(InputStream inputStream, int sheetIndex) throws IOException, InvalidFormatException {
		this.inputStream = inputStream;
		
		//Get the workbook instance for Excel file 
//		HSSFWorkbook workbook = new HSSFWorkbook(inputStream, false); // old constructor for xls files
		Workbook workbook = WorkbookFactory.create(inputStream);
		//Get first sheet from the workbook
		sheet = workbook.getSheetAt(sheetIndex);
		 
		rowIterator = sheet.iterator();
		 
	}

	@Override
	public String[] readNext() throws IOException {
		List<String> line = readLine();
		if (line == null) {
			return null;
		}
		String[] result = line.toArray(new String[line.size()]);
		return result;
	}

	@Override
	public void close() throws IOException {
		inputStream.close();
	}
	
	private int size = -1;

	@Override
	public String[] readHeader() throws IOException {
		List<String> line = readLine();
		size = line.size();
		String[] result = line.toArray(new String[size]);
		return result;
	}
	
	private List<String> readLine() {

		//Get iterator to all the rows in current sheet
		if (!rowIterator.hasNext()) {
			return null;
		}
		List<String> cells = new LinkedList<>();

		//Get iterator to all cells of current row
//		Iterator<Cell> cellIterator = row.cellIterator();
		boolean first = true;
		for (Cell cell : rowIterator.next()) {
			if (first) {
				for (int i=0,l=cell.getColumnIndex();i<l;i++) {
					cells.add(null);
				}
				first = false;
			}
			

			// case Excel Date (stored as double):
//			if (DateUtil.isCellDateFormatted(cell)) {
//				double doubleValue = cell.getNumericCellValue();
//				Date dateValue = DateUtil.getJavaDate(doubleValue, Member.getTimeZone());
//				if (dateValue != null) {
//					// Its an Excel Date
//					cells.add(Member.toString(dateValue));
//				} else {
//					cells.add(String.valueOf(doubleValue));
//				}
//			} else {
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_BOOLEAN:
					cells.add(String.valueOf(cell.getBooleanCellValue()));
					break;
				case Cell.CELL_TYPE_NUMERIC:
					double doubleValue = cell.getNumericCellValue();
					// case Excel Date (stored as double):
					Date dateValue;
					if (DateUtil.isCellDateFormatted(cell) &&
							(dateValue = DateUtil.getJavaDate(doubleValue, MemberUtils.getTimeZone())) != null) {
						cells.add(MemberUtils.toString(dateValue));
					} else {
						long longValue = (long) doubleValue;
						if (longValue == doubleValue) {
							cells.add(String.valueOf(longValue));
						} else {
							cells.add(String.valueOf(doubleValue));
						}
					}
					break;
				case Cell.CELL_TYPE_BLANK:
					cells.add(null);
					break;
				case Cell.CELL_TYPE_STRING:
					cells.add(cell.getStringCellValue().trim());
					break;
				case Cell.CELL_TYPE_ERROR:
					cells.add(null);
					break;
				case Cell.CELL_TYPE_FORMULA:
					try {
						cells.add(cell.getStringCellValue().trim());
					} catch (Exception e) {
						try {
							cells.add(String.valueOf(cell.getNumericCellValue()));
						} catch (Exception e1) {
							try {
								cells.add(String.valueOf(cell.getBooleanCellValue()));
							} catch (Exception e2) {
								cells.add(null);
							}
						}
					}
					break;
				default:
					try {
						cells.add(cell.getStringCellValue().trim());
					} catch (Exception e) {
						cells.add(null);
					}
					break;
				}
//			}
			
			
		}
		// To ensure the line array size, in case this line's last cells are empty:
		int nbElts = cells.size();
		for (int i=nbElts;i<size;i++) {
			cells.add(null);
		}
		// TODO voir s'il est possible de stocker les formats numériques sans les convertir en String (puis plus tard en int)
		return cells;
	}
	public static void main(String[] args) {
		double nbDouble = 2008;
		long nbLong = (long) nbDouble;
		System.out.println(nbDouble);
		System.out.println(nbLong);
		System.out.println(nbDouble == nbLong);
	}
}
